import React, { useState, useEffect, useRef } from 'react';
import { Tree, Typography, Modal, Input, message } from 'antd';
import { TreeNodeData } from '../types';
import './TreeSection.less';

const { Title } = Typography;

interface TreeSectionProps {
  title: string;
  treeData: TreeNodeData[];
  selectedKeys: string[];
  expandedKeys: string[];
  onSelect: (selectedKeys: any, info: any) => void;
  onExpand: (expandedKeys: any[]) => void;
  onContextMenuAction?: (action: string, nodeData: any, preSelected?: string[], actionType?: string) => void;
  className?: string;
}

export const TreeSection: React.FC<TreeSectionProps> = ({
  title,
  treeData,
  selectedKeys,
  expandedKeys,
  onSelect,
  onExpand,
  onContextMenuAction,
  className,
}) => {
  const [contextMenuVisible, setContextMenuVisible] = useState(false);
  const [contextMenuPosition, setContextMenuPosition] = useState({ x: 0, y: 0 });
  const [rightClickedNode, setRightClickedNode] = useState<any>(null);
  const [levelModalVisible, setLevelModalVisible] = useState(false);
  const [levelInputValue, setLevelInputValue] = useState('');
  const [currentAction, setCurrentAction] = useState<'expandN' | 'collapseN' | null>(null);
  const menuRef = useRef<HTMLDivElement>(null);

  // 获取兄弟节点（同级节点）
  const getSiblingNodes = (nodeKey: string): string[] => {
    const findParentAndSiblings = (nodes: TreeNodeData[], key: string, parent: TreeNodeData | null = null): string[] => {
      for (const node of nodes) {
        if (node.key === key) {
          // 找到目标节点，返回其兄弟节点
          if (parent && parent.children) {
            return parent.children
              .filter(sibling => sibling.key !== key) // 排除自己
              .map(sibling => sibling.key);
          }
          return [];
        }
        if (node.children) {
          const result = findParentAndSiblings(node.children, key, node);
          if (result.length > 0) return result;
        }
      }
      return [];
    };
    
    return findParentAndSiblings(treeData, nodeKey);
  };

  // 获取直接下级节点
  const getDirectChildren = (nodeKey: string): string[] => {
    const findNodeInTree = (nodes: TreeNodeData[], key: string): TreeNodeData | null => {
      for (const node of nodes) {
        if (node.key === key) return node;
        if (node.children) {
          const found = findNodeInTree(node.children, key);
          if (found) return found;
        }
      }
      return null;
    };
    
    const node = findNodeInTree(treeData, nodeKey);
    if (!node || !node.children) return [];
    
    const result: string[] = [];
    
    // 只获取直接下级节点，不包含更深层的子节点
    for (const child of node.children) {
      result.push(child.key);
    }
    
    return result;
  };

  // 获取节点汇总直接下级的所有相关节点（包含当前节点和直接下级）
  const getDirectChildrenWithSiblings = (nodeKey: string): string[] => {
    const result: string[] = [];
    
    // 1. 添加当前节点
    result.push(nodeKey);
    
    // 2. 添加直接下级节点
    const directChildren = getDirectChildren(nodeKey);
    result.push(...directChildren);
    
    // 去重并返回
    return [...new Set(result)];
  };

  // 获取所有下级节点（递归）
  const getAllChildren = (nodeKey: string): string[] => {
    const findNodeInTree = (nodes: TreeNodeData[], key: string): TreeNodeData | null => {
      for (const node of nodes) {
        if (node.key === key) return node;
        if (node.children) {
          const found = findNodeInTree(node.children, key);
          if (found) return found;
        }
      }
      return null;
    };
    
    const collectAllChildren = (node: TreeNodeData): string[] => {
      const result: string[] = [];
      if (node.children) {
        for (const child of node.children) {
          // 添加所有子节点，不判断是否有children
          result.push(child.key);
          result.push(...collectAllChildren(child));
        }
      }
      return result;
    };
    
    const node = findNodeInTree(treeData, nodeKey);
    if (!node) return [];
    
    const result: string[] = [];
    // 1. 添加当前节点
    result.push(nodeKey);
    // 2. 添加所有下级节点
    result.push(...collectAllChildren(node));
    
    return [...new Set(result)];
  };

  // 递归获取指定级数的所有子节点
  // 层级定义：如果一个节点有children，那么该节点和它的直接子节点被视为同一层级
  const getChildrenKeysRecursive = (nodeKey: string, level: number): string[] => {
    const findNodeInTree = (nodes: TreeNodeData[], key: string): TreeNodeData | null => {
      for (const node of nodes) {
        if (node.key === key) return node;
        if (node.children) {
          const found = findNodeInTree(node.children, key);
          if (found) return found;
        }
      }
      return null;
    };
    
    const node = findNodeInTree(treeData, nodeKey);
    if (!node) return [];
    
    // 使用层级队列来处理
    let currentLevelNodes = [node];
    const result: string[] = [];
    
    for (let i = 1; i <= level; i++) {
      const nextLevelNodes: TreeNodeData[] = [];
      
      // 处理当前层级的所有节点
      for (const currentNode of currentLevelNodes) {
        result.push(currentNode.key);
        
        // 收集下一层级的节点：当前节点的所有直接子节点
        if (currentNode.children) {
          for (const child of currentNode.children) {
            const childNode = findNodeInTree(treeData, child.key);
            if (childNode) {
              nextLevelNodes.push(childNode);
            }
          }
        }
      }
      
      // 准备处理下一层级
      currentLevelNodes = nextLevelNodes;
      
      // 如果没有更多节点了，提前结束
      if (currentLevelNodes.length === 0) {
        break;
      }
    }
    
    return result;
  };

  // 处理右键点击
  const handleRightClick = (info: any) => {
    const { event, node } = info;
    event.preventDefault();
    setRightClickedNode(node);
    setContextMenuPosition({ x: event.clientX, y: event.clientY });
    setContextMenuVisible(true);
    
    // 右键时自动选中该节点
    if (onSelect) {
      onSelect([node.key], { selectedNodes: [node], node });
    }
  };

  // 处理菜单项点击
  const handleMenuClick = (key: string) => {
    if (key === 'expand' && rightClickedNode) {
      // 展开本级节点
      const nodeKey = rightClickedNode.key;
      if (!expandedKeys.includes(nodeKey)) {
        onExpand([...expandedKeys, nodeKey]);
      }
    } else if (key === 'collapse' && rightClickedNode) {
      // 收缩本级节点
      const nodeKey = rightClickedNode.key;
      if (expandedKeys.includes(nodeKey)) {
        onExpand(expandedKeys.filter(key => key !== nodeKey));
      }
    } else if (key === 'expandN' || key === 'collapseN') {
      // 展开或收缩N级节点，需要输入级数
      setCurrentAction(key);
      setLevelInputValue('');
      setLevelModalVisible(true);
    } else if (key === 'summaryDirect' && rightClickedNode) {
      // 节点汇总直接下级（包含当前节点、兄弟节点和直接下级）
      const allRelatedNodes = getDirectChildrenWithSiblings(rightClickedNode.key);
      if (allRelatedNodes.length > 1) { // 至少包含当前节点，所以大于1才有意义
        // 触发合并报表弹窗，并传递预选中的相关节点
        if (onContextMenuAction) {
          onContextMenuAction('merge', rightClickedNode, allRelatedNodes, 'summaryDirect');
        }
      } else {
        message.warning('当前节点没有可合并的相关节点');
      }
    } else if (key === 'summaryAll' && rightClickedNode) {
      // 节点汇总所有下级
      const allChildren = getAllChildren(rightClickedNode.key);
      if (allChildren.length > 1) { // 至少包含当前节点，所以大于1才有意义
        // 触发合并报表弹窗，并传递预选中的所有下级节点
        if (onContextMenuAction) {
          onContextMenuAction('merge', rightClickedNode, allChildren, 'summaryAll');
        }
      } else {
        message.warning('当前节点没有可合并的相关节点');
      }
    } else if (onContextMenuAction && rightClickedNode) {
      onContextMenuAction(key, rightClickedNode);
    }
    setContextMenuVisible(false);
  };

  // 处理级数输入确认
  const handleLevelConfirm = () => {
    const level = parseInt(levelInputValue);
    if (isNaN(level) || level <= 0) {
      message.error('请输入有效的正整数');
      return;
    }

    if (!rightClickedNode) return;

    const nodeKey = rightClickedNode.key;
    const targetKeys = getChildrenKeysRecursive(nodeKey, level);

    if (currentAction === 'expandN') {
      // 展开N级节点（从当前节点开始的N级）
      const newExpandedKeys = [...new Set([...expandedKeys, ...targetKeys])];
      onExpand(newExpandedKeys);
    } else if (currentAction === 'collapseN') {
      // 收缩N级节点（从当前节点开始的N级）
      const keysToRemove = new Set(targetKeys);
      const newExpandedKeys = expandedKeys.filter(key => !keysToRemove.has(key));
      onExpand(newExpandedKeys);
    }

    setLevelModalVisible(false);
    setCurrentAction(null);
    setLevelInputValue('');
  };

  // 处理级数输入取消
  const handleLevelCancel = () => {
    setLevelModalVisible(false);
    setCurrentAction(null);
    setLevelInputValue('');
  };

  // 处理点击外部关闭菜单
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (menuRef.current && !menuRef.current.contains(event.target as Node)) {
        setContextMenuVisible(false);
      }
    };

    if (contextMenuVisible) {
      document.addEventListener('mousedown', handleClickOutside);
      return () => {
        document.removeEventListener('mousedown', handleClickOutside);
      };
    }
  }, [contextMenuVisible]);

  return (
    <div className={`tree-section-container ${className || ''}`}>
      {/* <Title level={5} style={{ margin: '8px 0', fontSize: 12 }}>
        {title}
      </Title> */}
      <Tree
        className="custom-tree"
        showIcon
        showLine={{ showLeafIcon: false }}
        selectedKeys={selectedKeys}
        expandedKeys={expandedKeys}
        onSelect={onSelect}
        onExpand={onExpand}
        onRightClick={handleRightClick}
        treeData={treeData}
      />
      
      {/* 自定义定位的右键菜单 */}
      {contextMenuVisible && (
        <div
          ref={menuRef}
          className="tree-context-menu"
          style={{
            left: contextMenuPosition.x,
            top: contextMenuPosition.y,
          }}
        >
          <div
            className="menu-item"
            onClick={() => handleMenuClick('expand')}
          >
            展开本级节点
          </div>
          <div
            className="menu-item"
            onClick={() => handleMenuClick('collapse')}
          >
            收缩本级节点
          </div>

          <div
            className="menu-item"
            onClick={() => handleMenuClick('expandN')}
          >
            展开N级节点
          </div>
          <div
            className="menu-item"
            onClick={() => handleMenuClick('collapseN')}
          >
            收缩N级节点
          </div>
          <div
            className="menu-item"
            onClick={() => handleMenuClick('summaryDirect')}
          >
            节点汇总直接下级
          </div>
          <div
            className="menu-item"
            onClick={() => handleMenuClick('summaryAll')}
          >
            节点汇总所有下级
          </div>



        </div>
      )}
      
      {/* 级数输入弹窗 */}
      <Modal
        title={currentAction === 'expandN' ? '展开N级节点' : '收缩N级节点'}
        open={levelModalVisible}
        onOk={handleLevelConfirm}
        onCancel={handleLevelCancel}
        okText="确定"
        cancelText="取消"
      >
        <div style={{ marginBottom: 16 }}>
          请输入要{currentAction === 'expandN' ? '展开' : '收缩'}的级数：
        </div>
        <Input
        size='large'

          type="number"
          value={levelInputValue}
          onChange={(e) => setLevelInputValue(e.target.value)}
          placeholder="请输入正整数"
          min={1}
          onPressEnter={handleLevelConfirm}
        />
      </Modal>
    </div>
  );
};
